//
//  ST_BTEmojiGroupCell.swift
//  btvideo
//
//  Created by mac on 2020/7/15.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyAttributes

class ST_BTEmojiGroupCell: UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
//    MARK: - Properties
    
    fileprivate var visual_effect_view:ST_CustomIntensityVisualEffectView?
    
    fileprivate lazy var share_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xFEC207)
        control.cornerRadius = 40/2.0
        control.setTitleForAllStates("我们来吧!")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.addTarget(self, action: #selector(share_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var share_label:UILabel = {
        let control = UILabel()
        return control
    }()
    
    fileprivate lazy var need_share_label:UILabel = {
        let control = UILabel()
        control.textColor = UIColor.init(hex: 0xACB4C0)
        control.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        
        return control
    }()
    
    
    fileprivate lazy var share_icon_image_view:UIImageView = {
         let control = UIImageView()
          control.contentMode = .scaleAspectFill
          return control
      }()

    fileprivate lazy var share_root_view:UIView = {
        let control = UIView()
        
        control.addSubview(share_icon_image_view)
        
        share_icon_image_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(80)
            make.height.equalTo(80)
            make.top.equalToSuperview().offset(25)
        }
        
        control.addSubview(share_btn)
        share_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(95)
            make.height.equalTo(40)
            make.top.equalTo(share_icon_image_view.snp.bottom).offset(50)
        }
        
        control.addSubview(share_label)
        share_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(share_icon_image_view.snp.bottom).offset(15)
            make.height.equalTo(20)
        }
        
        control.addSubview(need_share_label)
        need_share_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(share_btn.snp.bottom).offset(10)
            make.height.equalTo(17)
        }
        
        return control
    }()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
//        controlLayout.scrollDirection = .vertical
//         controlLayout.minimumLineSpacing = 10
         controlLayout.minimumInteritemSpacing = 10
         controlLayout.itemSize = CGSize.init(width: 55, height: 55)
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 44, right: 10)
        return controlLayout
    }()
        
     
     fileprivate lazy var collectionView:UICollectionView = {
         let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
//         control.isPagingEnabled = true
         control.backgroundColor = UIColor.white
         control.delegate = self
         control.dataSource = self

         control.register(cellWithClass: ST_BTEmojiChildCell.self)
         
         control.showsVerticalScrollIndicator = false
         control.showsHorizontalScrollIndicator = false
         if #available(iOS 11.0, *) {
             control.contentInsetAdjustmentBehavior = .never
         }
         return control
     }()
    
    var model:ST_EmojiGroupModel?{
        didSet{
            
            guard let m = model,let a = ST_BTUserInfoManager.shared.additional_attributes else { return  }
            
            self.array = m.emojiDetail
            
            if a.countOfInvited < m.inviteNum{
                create_visual_effect()
            }else{
                remove_visual_effect()
            }
            
        }
    }
    
    
    func create_visual_effect()  {
        
        
        self.visual_effect_view?.removeFromSuperview()
        self.share_root_view.removeFromSuperview()
        
       let eView = ST_CustomIntensityVisualEffectView.init(effect: UIBlurEffect(style: .light), intensity: 0.2)
            
        self.visual_effect_view = eView
        
        contentView.insertSubview(eView, aboveSubview: collectionView)
        
        eView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        contentView.insertSubview(share_root_view, aboveSubview: eView)
        
        share_root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        guard let m = model else { return  }
        
        let str = "邀请".withAttributes([Attribute.textColor(UIColor.init(hex: 0x333333)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))])
        
        let str0 = m.inviteNum.string.withAttributes([Attribute.textColor(UIColor.init(hex: 0xFEC207)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))])
        
        let str1 = "位好友加入伴心，解锁这个表情包".withAttributes([Attribute.textColor(UIColor.init(hex: 0x333333)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.semibold))])
        
        str.append(str0)
        
        str.append(str1)
        
        share_label.attributedText = str
        
        
        need_share_label.text = "再鼓励 \(m.inviteNum-(ST_BTUserInfoManager.shared.additional_attributes?.countOfInvited ?? 0)) 个好友加入"
        
        
        share_icon_image_view.pin_setImage(from: m.coverImg.url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
    }
    
    func remove_visual_effect()  {
        
        visual_effect_view?.removeFromSuperview()
        
        share_root_view.removeFromSuperview()
        
    }
    
    var selected_closure:((BTEmojiItemModel)->())?
   
    private(set) var array = [BTEmojiItemModel](){
        didSet{
            self.collectionView.reloadData()
        }
    }
    
}

extension ST_BTEmojiGroupCell{
    
    @objc fileprivate func share_handle(){
        
        let vc = ST_ShareMyAppController()
        
        vc.overCurrentContext = true
        
        GlobalPresent(toController: vc)
        
    }
    
}

//MARK: -
extension ST_BTEmojiGroupCell:UICollectionViewDelegate,UICollectionViewDataSource{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_BTEmojiChildCell.self, for: indexPath)
        
        cell.model = array[safe:indexPath.row]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        selected_closure?(array[indexPath.row])
    }
    
}



//MARK: - Model
class ST_EmojiGroupModel : NSObject{

    var bottomImg : String!
    var coverImg : String!
    var emojiDetail : [BTEmojiItemModel]!
    var id : Int!
    var inviteNum : Int!
    var name : String!
    var sort : Int!

    /**
     * Instantiate the instance using the passed json values to set the properties values
     */
    init(fromJson json: JSON){
        
        bottomImg = json["bottom_img"].stringValue
        coverImg = json["cover_img"].stringValue
        
        emojiDetail = [BTEmojiItemModel]()
        let emojiDetailArray = json["emoji_detail"].arrayValue
        
        for emojiDetailJson in emojiDetailArray{
            let value = BTEmojiItemModel(fromJson: emojiDetailJson)
            emojiDetail.append(value)
        }
        id = json["id"].intValue
        inviteNum = json["invite_num"].intValue
        name = json["name"].stringValue
        sort = json["sort"].intValue
        
        super.init()
    }
}
